package pl.edu.uj.tcs.blef.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;


public class TableConnectionHandler extends Thread {
	private Socket socket;
	private Table table;
	private BufferedReader inputStream;
	private boolean isOperator;
	
	public TableConnectionHandler(Table table, Socket socket) throws IOException{
		this.table = table;
		this.socket = socket;
		this.isOperator = false;
		this.inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
		if(table.getPlayers().size() == 0){
			System.out.println("Operator has joined the table at " + table.getPort());
			Client operator = new Client(table.getOperatorName(), socket, 1);
			table.getPlayers().add(operator);
			table.setOperator(operator);
			this.isOperator = true;
		}
		
		start();
	}
	
	@Override
	public void run(){
		String inputLine = new String();
		try {
			while(true){		
				inputLine = inputStream.readLine();
				if(inputLine == null){
					this.table.getListener().decrementConnections();
					this.table.removeConnection(socket);
					this.table.checkTerminate();
					System.out.println("Table connection broke with " + socket.getInetAddress().getHostAddress());
					return;
				}
				
				System.out.println("Try to parse TABLE:" + socket.getLocalPort() + " message: " + inputLine);
				table.getHeadquarters().parse(inputLine, socket);
			} 
		} catch (IOException e) {
			if(this.isOperator) table.setOperator(null);
			this.table.getListener().decrementConnections();
			this.table.removeConnection(socket);
			this.table.checkTerminate();
			System.out.println("Table connection broke with " + socket.getInetAddress().getHostAddress());		
		}
	}
}
